package com.imooc.demo.springboot.es.controller;

import com.imooc.demo.springboot.es.entity.es.EsBlog;
import com.imooc.demo.springboot.es.entity.mysql.MysqlBlog;
import com.imooc.demo.springboot.es.repository.es.EsBlogRepository;
import com.imooc.demo.springboot.es.repository.mysql.MysqlRepository;
import lombok.Data;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * Created by hu on 2019/12/22.
 */
@RestController
public class DataController {

    @Autowired
    MysqlRepository mysqlRepository;

    @Autowired
    EsBlogRepository esBlogRepository;

    @GetMapping("/blogs")
    public Object blog(){
        List<MysqlBlog> mysqlBlogs = mysqlRepository.queryAll();
        return mysqlBlogs;
    }

    @PostMapping("/search")
    public Object search(@RequestBody Param param){
        HashMap<String, Object> map = new HashMap<>();
        StopWatch watch = new StopWatch();
        watch.start();
        String type = param.getType();
        String keyword = param.getKeyword();
        if (type.equalsIgnoreCase("mysql")){
            //mysql
            List<MysqlBlog> blogList = mysqlRepository.queryBlogs(keyword);
            map.put("list", blogList);

        }else if (type.equalsIgnoreCase("es")){
            //es
            BoolQueryBuilder builder = QueryBuilders.boolQuery();
            builder.should(QueryBuilders.matchPhraseQuery("title", keyword));
            builder.should(QueryBuilders.matchPhraseQuery("content", keyword));
            String s = builder.toString();
            System.out.println(s);

            Page<EsBlog> search = (Page<EsBlog>) esBlogRepository.search(builder);
            List<EsBlog> content = search.getContent();
            map.put("list", content);
        }else {
            return "false";
        }
        watch.stop();
        long sumTime = watch.getTotalTimeMillis();
        map.put("duration", sumTime);
        return map;
    }

    @Data
    public static class Param{
        //mysql,es
        private String type;

        private String keyword;
    }
}
